package lipengfei.botaiframework.utils.num;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @author lipf
 * 建设银行16位数字不重复, 不支持分布式或集群使用
 * MMddhhmmss+4位随机数
 */
public class RequestSnUtil {

    private static   RequestSnUtil requestSnUtil;

    private   String snLockNo;

    private   List<String> snList ;


    public static synchronized RequestSnUtil getInstance() {
        requestSnUtil = new RequestSnUtil();
        requestSnUtil.setSnLockNo(new SimpleDateFormat("MMddhhmmss").format(new Date()));
        requestSnUtil.setSnList(new ArrayList<String>());
        return requestSnUtil;
    }

    public  synchronized   String getRequestSn() {
        String snLockNoNew = new SimpleDateFormat("MMddhhmmss").format(new Date());
        if(!snLockNoNew.equals(this.snLockNo)){
            this.snLockNo = snLockNoNew;
            snList.clear();
        }

        String  requestSn = null;
        int i=0;
        while (true){
            i++;
            requestSn = snLockNo+String.format("%04d",new Random().nextInt(9999));
            if(!snList.contains(requestSn)){
                snList.add(requestSn);
                break;
            }else{
                if(i>=10000){
                    break;
                }
            }
        }
       return requestSn;
    }

    public String getSnLockNo() {
        return snLockNo;
    }

    public void setSnLockNo(String snLockNo) {
        this.snLockNo = snLockNo;
    }


    public void setSnList(ArrayList<String> snList) {
        this.snList = snList;
    }



}
